package org.example.kidscode.service.impl;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.kidscode.entity.Student;
import org.example.kidscode.repository.StudentRepository;
import org.example.kidscode.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceImpl implements StudentService {

    private final StudentRepository studentRepository;

    // 日期格式解析器，假设日期格式为 yyyy-MM-dd
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public StudentServiceImpl(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @Override
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    @Override
    public Optional<Student> findById(String id) {
        return studentRepository.findById(id);
    }

    @Override
    public Student save(Student student) {
        return studentRepository.save(student);
    }

    @Override
    public void deleteById(String id) {
        studentRepository.deleteById(id);
    }

    // 批量导入学生数据（Excel）
    @Override
    public void importStudentsFromExcel(MultipartFile file) throws Exception {
        InputStream is = file.getInputStream();
        Workbook workbook = new XSSFWorkbook(is);
        Sheet sheet = workbook.getSheetAt(0);

        List<Student> students = new ArrayList<>();

        for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 跳过表头
            Row row = sheet.getRow(i);
            if (row == null) continue;

            Student student = new Student();
            student.setStudentId(getCellValue(row.getCell(0)));
            student.setName(getCellValue(row.getCell(1)));

            String genderStr = getCellValue(row.getCell(2));
            student.setGender("男".equals(genderStr) ? "M" : "F");

            // age 转 Short 类型
            student.setAge((short) parseIntSafe(getCellValue(row.getCell(3))));

            // birthday 解析为 Date
            student.setBirthday(parseDateSafe(getCellValue(row.getCell(4))));

            student.setSchool(getCellValue(row.getCell(5)));
            student.setGrade(getCellValue(row.getCell(6)));
            student.setContactPhone(getCellValue(row.getCell(7)));
            student.setParentName(getCellValue(row.getCell(8)));
            student.setParentPhone(getCellValue(row.getCell(9)));
            student.setCurrentLevel(getCellValue(row.getCell(10)));

            // enrollmentDate 解析为 Date
            student.setEnrollmentDate(parseDateSafe(getCellValue(row.getCell(11))));

            student.setStatus(true);
            student.setRemark(getCellValue(row.getCell(12)));

            // 如果手机号不存在才插入
            if (!studentRepository.existsByContactPhone(student.getContactPhone())) {
                students.add(student);
            }
        }

        studentRepository.saveAll(students);
        workbook.close();
    }

    // 获取单元格字符串值
    private String getCellValue(Cell cell) {
        if (cell == null) return "";
        if (cell.getCellType() == CellType.NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                // 格式化日期为 yyyy-MM-dd
                return sdf.format(cell.getDateCellValue());
            } else {
                return String.valueOf((long) cell.getNumericCellValue());
            }
        }
        return cell.toString().trim();
    }

    // 安全转换字符串为整数
    private int parseIntSafe(String value) {
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            return 0;
        }
    }

    // 安全转换字符串为日期
    private Date parseDateSafe(String dateStr) {
        try {
            if (dateStr == null || dateStr.isEmpty()) return null;
            return sdf.parse(dateStr);
        } catch (Exception e) {
            return null;
        }
    }
}
